﻿/*
    a03_Delegate @ https://gitee.com/zcatt/MyDemo2020

delegate的使用
*/
using System;
using System.Collections;

public struct Person
{
    public string m_name;
    public bool m_isMale;
    public float m_height;
    public int m_age;

    public Person(string name, bool isMale, float height, int age)
    {
        m_name = name;
        m_isMale = isMale;
        m_height = height;
        m_age = age;
    }
}

public delegate void ProcessPerson(Person person);

public class PersonDB
{
    ArrayList list = new ArrayList();

    public void addPerson(string name, bool isMale, float height, int age)
    {
        list.Add(new Person(name, isMale, height, age));
    }

    public void processPersons(ProcessPerson processPerson)
    {
        foreach(Person e in list)
        {
            processPerson(e);
        }
    }
}

public class AverageHeight
{
    public float m_heightSum;
    public int m_count;
    public void calcAverageHeight(Person person)
    {
        m_heightSum += person.m_height;
        m_count++;
    }

    public float averageHeight()
    {
        return m_heightSum / m_count;
    }
}

class Program
{
    static void printJhone(Person person)
    {
        if (person.m_name.IndexOf("Jhon") >= 0)
            Console.WriteLine(person.m_name);
    }
    static void Main(string[] args)
    {
        PersonDB db = new PersonDB();
        addPersons(db);

        Console.WriteLine("Persons with 'Jhon':");
        db.processPersons(new ProcessPerson(printJhone));

        Console.Write("Average height:  ");
        AverageHeight ah = new AverageHeight();
        db.processPersons(new ProcessPerson(ah.calcAverageHeight));
        Console.WriteLine("{0} m", ah.averageHeight()/100);

        return;
    }

    static void addPersons(PersonDB db)
    {
        db.addPerson("Jhon Smith", true, 175, 30);
        db.addPerson("Jhon Tom", false, 185, 40);
        db.addPerson("Tom Smith", true, 190, 50);
        db.addPerson("Harry Smith", false, 165, 30);
        db.addPerson("Jhon Harry", true, 171, 40);
        db.addPerson("Marry Smith", false, 169, 50);
        db.addPerson("Jhon Marry", true, 183, 30);
        db.addPerson("Gim Matt", false, 172, 40);

    }
}
